package cn.xiaopengstack.domain.trade.rule.settlement;

import cn.xiaopengstack.domain.trade.rule.factory.SettlementRuleFilterFactory;
import cn.xiaopengstack.domain.trade.model.entity.MarketOrderEntity;
import cn.xiaopengstack.domain.trade.model.entity.SettlementRuleCommandEntity;
import cn.xiaopengstack.domain.trade.model.entity.SettlementRuleResponseEntity;
import cn.xiaopengstack.domain.trade.repository.ITradeRepository;
import cn.xiaopengstack.types.enums.ResponseCode;
import cn.xiaopengstack.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * @author jiangyangang
 */
@Component
@Slf4j
public class TradeOrderValidateFilter extends AbstractSettlementLogicLink<SettlementRuleCommandEntity, SettlementRuleFilterFactory.DynamicContext, SettlementRuleResponseEntity> {

    public TradeOrderValidateFilter(ITradeRepository tradeRepository) {
        super(tradeRepository);
    }

    @Override
    public SettlementRuleResponseEntity apply(SettlementRuleCommandEntity request, SettlementRuleFilterFactory.DynamicContext dynamic) throws Exception {
        log.info("结算规则流。交易订单校验节点开始");

        Optional<MarketOrderEntity> marketOrderEntity = tradeRepository.queryUnPayMarketPayOrder(request.getUserId(), request.getOutTradeNo());
        // 不存在未支付的订单
        MarketOrderEntity marketOrder = marketOrderEntity.orElseThrow(() -> new AppException(ResponseCode.TRADE_EMPTY_ORDER.getCode(), ResponseCode.TRADE_EMPTY_ORDER.getInfo()));

        dynamic.setMarketOrderEntity(marketOrder);

        return next(request, dynamic);
    }

}
